package com.alatus.web;

import com.alatus.constant.Constants;
import com.alatus.model.TActivity;
import com.alatus.query.ActivityQuery;
import com.alatus.result.Result;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.alatus.service.ActivityService;

import java.util.Arrays;
import java.util.List;

@RestController
public class ActivityController {
    @Resource
    private ActivityService activityService;

    @PreAuthorize(value = "hasAuthority('activity:list')")
    @GetMapping(value = "/api/activities")
    public Result activityPage(@RequestParam(value = Constants.CURRENT,required = false)Integer current,
                               ActivityQuery activityQuery){
        if(current == null){
            current = 1;
        }
//        返回结果为PageInfo
        PageInfo<TActivity> activityByPage = activityService.getActivityByPage(current,activityQuery);
        return Result.OK(activityByPage);
    }

    @PreAuthorize(value = "hasAuthority('activity:add')")
    @PostMapping(value = "/api/activity/add")
    public Result addActivity(ActivityQuery activityQuery, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        activityQuery.setToken(token);
        int result = activityService.saveActivity(activityQuery);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('activity:delete')")
    @DeleteMapping(value = "/api/activity/delete/{id}")
    public Result deleteActivty(@PathVariable(value = Constants.ID)Integer id){
        int result = activityService.deleteActivtyById(id);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('activity:view')")
    @GetMapping(value = "/api/activity/{id}")
    public Result activityDetail(@PathVariable(value = Constants.ID)Integer id){
        TActivity tActivity = activityService.getActivityById(id);
        return Result.OK(tActivity);
    }

    @PreAuthorize(value = "hasAuthority('activity:delete')")
    @DeleteMapping(value = "/api/activity/batchDel")
    public Result activityBatchDel(@RequestParam(value = Constants.IDS)String ids, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        List<String> idList = Arrays.asList(ids.split(","));
        int result = activityService.delActivityByIds(idList);
        return result >= idList.size() ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('activity:edit')")
    @PutMapping(value = "/api/activity/edit")
    public Result editActivity(ActivityQuery activityQuery, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        activityQuery.setToken(token);
        int result = activityService.updateActivity(activityQuery);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }
}
